package com.ftg.learn.mybatis.chapter3.config;


import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * 通过这个java来完成对mybatis配置
 * @author kangjx
 * @date 2022/10/13
 */
public class SessionUtil {

    private final String url = "jdbc:mysql://localhost:3306/learn07?serverTimezone=UTC";
    private final String username = "root";
    private final String password = "Love0913@kjx";
    private final String driverClass = "com.mysql.cj.jdbc.Driver";

    /**
     * 初始化配置信息，用mybatis核心提供参数支撑
     * @return Configuration
     */
    private Configuration initConfiguration(){
        Configuration conf = new Configuration();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        PooledDataSource dataSource = new PooledDataSource(driverClass,url,username,password);
        Environment env = new Environment("mysql",transactionFactory,dataSource);
        conf.setEnvironment(env);

        conf.setLogImpl(StdOutImpl.class);
        conf.setLazyLoadingEnabled(true);

        conf.addMappers("com.ftg.learn.mybatis.chapter3.mapper");

        return conf;
    }

    /**
     * 获得一个sqlSession
     * @param autocommit 自动提交操作
     * @return SqlSession
     */
    private SqlSession getSession(boolean autocommit){
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(this.initConfiguration());
        return sqlSessionFactory.openSession(autocommit);
    }

    /**
     * 返回一个事务自动提交的sqlSession
     * @return
     */
    public SqlSession getAutoCommitSession(){
        return this.getSession(true);
    }

    /**
     * 返回一个事务手动提交提交的sqlSession
     * @return
     */
    public SqlSession getNoAutoCommitSession(){
        return this.getSession(false);
    }


}
